<template>

  <div class="flie">

    <div v-if="userInfo">

      <el-input class="input" v-model="share" placeholder="请输入分享码">
        <template #append>
          <el-button @click="pushFileList">添加</el-button>
        </template>
      </el-input>
      <el-card v-for="(item, index) in fileData" :key="index" class="card" shadow="hover">
        <div class="content">
          <div class="left">{{ item.filename }}</div>
          <div class="right">
            <el-button @click="getShareFile(item.filename, item.filePath, item.userID)">下载</el-button>
          </div>
        </div>
        <div class="bottom" v-if="item.progress > 0">
          <el-progress :stroke-width="5" :percentage="item.progress" :status="item.status" />
        </div>
      </el-card>
    </div>



  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { useUserStore } from '@/stores/userStore';
const store = useUserStore();

const userInfo = computed(() => store.user);

interface FileDataItem {
  filename: string;
  filePath: string;
  userID: string;
  fileSize: number;
  progress: number; // 新增进度属性  
  status: any;   // 新增状态属性  
  // ...可能还有其他属性...  
}
const fileData = ref<FileDataItem[]>([]); // 创建一个响应式引用来存储文件数据  

const share = ref()


async function pushFileList() {
  try {

    // 使用split方法按'/'分割字符串  
    const parts = share.value.split('/');

    // 检查分割后的数组长度，以确保有两部分  
    if (parts.length === 2) {
      const shareID = parts[0];
      const filePass = parts[1];

      const url = `/api/file/findShareFile/${shareID}`;
      const params = {
        filePass: filePass,
        email: userInfo.value.email
      }
      const response = await axios.get(url, { params });
      // @ts-ignore
      store.addSharedFile(response.data.data);

      // 直接从store中获取最新的sharedFiles并映射到fileData  
      fileData.value = store.sharedFiles.map(item => ({
        ...item,
        progress: 0,
        status: ''
      }));

      if (response.data.code === '200') {
        ElMessage({
          message: '操作成功',
          type: 'success',
        });
      }
      if (response.data.code === '-1') {
        ElMessage({
          message: '操作失败:' + response.data.msg,
          type: 'error',
        });
      }


      fileData.value = store.sharedFiles.map(item => ({
        ...item, // 保留原有属性  
        progress: 0, // 设置初始进度为0  
        status: ''   // 设置初始状态为空字符串（或者'waiting'）  
      }));


    } else {
      console.error("The string does not contain exactly one '/' character.");
      ElMessage({
        message: '分享链接格式不正确',
        type: 'error',
      });
    }

  } catch (error) {
    console.error('操作失败:', error);
    ElMessage({
      message: '操作失败: ' + error.message, // 更具体地显示错误信息  
      type: 'error',
    });
  }
}




async function getShareFile(filename: string, filepath: string, uploadUserID: string) {
  try {
    const url = `/api/file/downloadFileByShareID?filePath=${filepath}&downloadUserID=${userInfo.value.email}&uploadUserID=${uploadUserID}`;

    // 查找要下载的文件项以获取fileSize  
    const fileItem = fileData.value.find(item => item.filename === filename && item.userID === uploadUserID);
    if (!fileItem) {
      throw new Error('无法找到文件项进行下载');
    }

    // 检查文件大小是否小于5MB（5MB = 5 * 1024 * 1024 字节）  
    const isFileSmall = fileItem.fileSize < (5 * 1024 * 1024);



    // 发送GET请求，设置响应类型为blob  
    const response = await axios.get(url, {
      responseType: 'blob',
      onDownloadProgress: function (progressEvent) {
        if (progressEvent.lengthComputable && !isFileSmall) { // 只在文件大于5MB时更新进度条  
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          updateProgressBar(filepath, uploadUserID, percentCompleted);
        }
      }
    });
    console.log(response);
    // 如果需要打印原始filename  
    console.log(filename);

    // 尝试从content-disposition头中获取文件名（可选）  
    let fileNameFromDisposition = '';
    const contentDisposition = response.headers['content-disposition'];
    if (contentDisposition && contentDisposition.includes('attachment')) {
      const matches = contentDisposition.match(/filename="(.*?)"/);
      if (matches && matches[1]) {
        fileNameFromDisposition = matches[1];
      }
    }

    // 如果从content-disposition中没有获取到文件名，则使用传入的filename  
    const downloadFileName = fileNameFromDisposition || filename;

    // 创建Blob对象，并生成一个指向它的URL  
    const blob = new Blob([response.data], { type: response.headers['content-type'] || 'application/octet-stream' });
    const downloadUrl = URL.createObjectURL(blob);

    // 创建一个隐藏的<a>元素来触发下载  
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = downloadFileName; // 设置下载文件的默认名称  
    document.body.appendChild(link);

    // 模拟点击下载  
    link.click();

    // 清理资源  
    URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);

    // 手动触发进度更新到100%，并设置状态为'success'  
    updateProgressBar(filepath, uploadUserID, 100);



    ElMessage({
      message: '操作成功',
      type: 'success',
    });

  } catch (error) {
    ElMessage({
      message: '操作失败:' + error,
      type: 'error',
    });
  }
}



function updateProgressBar(filepath: string, uploadUserID: string, percent: number) {
  const fileItem = fileData.value.find(item => item.filePath === filepath && item.userID === uploadUserID);
  if (fileItem) {
    fileItem.progress = percent;
    fileItem.status = percent >= 100 ? 'success' : '';
  } else {
    console.warn(`未找到文件项以更新进度条: ${filepath}, ${uploadUserID}`); // 如果找不到，发出警告  
  }
}
onMounted(() => {
  if (store.sharedFiles) {
    fileData.value = store.sharedFiles.map(item => ({
      ...item,
      progress: 0,
      status: ''
    }));
  }
})


</script>

<style scoped>
.card {
  width: 800px;
  margin-bottom: 10px;

}

.content {
  display: flex;
  justify-content: space-between;
}

.left {
  width: 60%;
  display: flex;
  justify-content: space-between;
  overflow: hidden;
  white-space: nowrap;
  /* 防止文本换行 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */

}

.right {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.bottom {
  width: 600px;
}

.input {
  margin-bottom: 30px;
  max-width: 600px
}
</style>